package mt.dummy;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;


/**
 * Thread class for server communication class.
 * A DealClient contains a Socket, an ObjectOutputStream, an ObjectInputStream,
 * a ServerCommDummy and a nickname
 * 
 * @author Grupo45
 *
 */

public class DealWithClient extends Thread {

	private String nickname;
	private ServerCommDummy servercomm;
	private Socket socket;
	private ObjectOutputStream out;
	private ObjectInputStream in;


	/**
	 * Constructor
	 * 
	 * @param socket socket of connection established
	 * @param servercomm communication server class
	 * @throws IOException Thrown if a connection cannot be established 
	 * @throws ClassNotFoundException Thrown if the class cannot be found
	 */
	public DealWithClient (Socket socket, ServerCommDummy servercomm){
		this.socket=socket;
		this.servercomm = servercomm;
		try {
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
			nickname = (String) in.readObject();

			System.out.println(nickname);


		} catch (IOException e) {
		} catch (ClassNotFoundException e) {
		}
	}

	/**
	 * Receives messages from client and send them to ServerComm
	 * 
	 * @throws ClassNotFoundException Thrown if the class cannot be found
	 * @throws IOException Thrown if a connection cannot be established
	 */
	public void run(){
		ServerMessage message;
		while(true){
			message = null;
			try {
				message = (ServerMessage) in.readObject();
				servercomm.addMessage(message);


			} catch (ClassNotFoundException e) {

			} catch (IOException e) {

			}
		}
	}

	/**
	 * Gets nickname of client
	 * 
	 * @return nickname 
	 */
	public String getNickname() {
		return nickname;
	}

	/**
	 * Send an order to a client
	 * 
	 * @param clientMessage
	 */
	public void sendOrder(ClientMessage clientMessage){
		try {
			out.writeObject(clientMessage);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Disconnect client
	 * 
	 * @throws IOException Thrown if a connection cannot be established
	 */
	public void disconnect() {
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * Send Error from Server to Client
	 * @param clientMessage
	 */


	public void sendError(ClientMessage clientMessage) {
		try {
			out.writeObject(clientMessage);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
